package com.alpha.realife.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @version V1.0
 * @author: Albert
 * @date: 2020/4/13 17:32
 * @description:
 */
@Component
public class JedisUtil {

    @Autowired
    JedisPool jedisPool;


    public String set(String redisKey, String redisValue) {

        Jedis resource = null;
        String setRStr = null;

        try {
            resource = jedisPool.getResource();
            setRStr = resource.set(redisKey, redisValue);
        } catch (Exception e) {

        } finally {
            if (null != resource) {
                resource.close();
            }
        }

        if (null == setRStr) {
            return "";
        }

        return setRStr;
    }


    /**
     * 获取对应key的过期时间
     *
     * @param redisKey
     * @return
     */
    public long getRedisElementExpire(String redisKey) {

        Long ttl = null;
        Jedis resource = null;
        try {
            resource = jedisPool.getResource();
            ttl = resource.ttl(redisKey);
        } catch (Exception e) {

        } finally {
            if (null != resource) {
                resource.close();
            }
        }

        if (null != ttl) {
            return ttl;
        }

        return 0L;
    }


    public void sAdd(String constant, String newFileName) {

        Jedis resource = null;
        try {
            resource = jedisPool.getResource();
            resource.sadd(constant, newFileName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != resource) {
                resource.close();
            }
        }
    }

    public String setex(String key, int seconds, String value) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.setex(key, seconds, value);
        } catch (Exception e) {

        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return "";
    }


    public String get(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.get(key);
        } catch (Exception e) {

        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return "";
    }


    public Long del(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.del(key);
        } catch (Exception e) {

        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return 0L;
    }
}
